import 'dart:io';

import 'package:dia/dia.dart';
import 'package:dia_static/dia_static.dart';
import 'package:path_provider/path_provider.dart';

import '../logger.dart';

abstract class LocalServer {
  static const _portMin = 8888;
  static int _port = _portMin;
  static remoteM3u82Local({required int videoId}) {
    return 'http://localhost:$_port/$videoId/index.m3u8';
  }

  static Future<bool> setup() async {
    final app = App();
    final Directory documents = await getApplicationDocumentsDirectory();
    final home = "${documents.path}/downloads/video";
    app.use(serve(home));
    _port = _portMin;
    for (var i = 0; i < 16; i++) {
      try {
        await app.listen('localhost', _port);
        logger.d('LocalServer listen success at $_port');
        return true;
      } catch (e) {
        _port++;
        logger.d('LocalServer listen fail at $_port');
      }
    }
    return false;
  }
}
